<template>
  <div class="page-box">

    <el-form class="search">
      <el-form-item label="分类">
        <el-cascader v-model="listModel.spuCategoryId" placeholder="选择分类" :props="listCascaderProps" @change="listCategoryChange" style="width: 300px;" clearable />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="listModel.spuBrandId" placeholder="选择品牌" clearable>
          <el-option v-for="item in listBrands" :key="item.id" :label="item.brandName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="listModel.spuTitle" placeholder="产品名称关键字" clearable />
      </el-form-item>
      <el-form-item label="上下架">
        <el-select v-model="listModel.spuSaleable" placeholder="选择是否上下架" clearable>
          <el-option v-for="item in saleableList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有效">
        <el-select v-model="listModel.spuValid" placeholder="选择是否有效" clearable>
          <el-option v-for="item in validList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-btn">
        <el-button type="primary" icon="Search" @click="pageSizeChange">搜索</el-button>
        <el-button icon="RefreshRight" @click="resetList">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="head">
      <span class="title">产品SPU管理</span>
      <div class="toolbar">
        <el-button type="primary" icon="Plus" @click="addOrModify(null)">添加</el-button>
        <el-button type="primary" icon="Refresh" @click="fetchListData">刷新</el-button>
        <el-button type="danger" icon="Delete" @click="isShowDelDialog = true">批量删除</el-button>
      </div>
    </div>

    <div class="table">
      <el-table
          stripe
          v-loading="loading"
          :data="listData"
          row-key="id"
          @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column prop="spuTitle" label="产品名称" />
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="firstCategoryName" label="分类" #default="{ row }">
          {{ row.firstCategoryName }}<br/>{{ row.secondCategoryName }}<br/>{{ row.thirdCategoryName }}
        </el-table-column>
        <el-table-column prop="spuSaleable" label="上/下架" #default="{ row }">
          <el-switch v-model="row.spuSaleable" @change="spuSaleableChange(row)" />
        </el-table-column>
        <el-table-column prop="spuValid" label="是否有效" #default="{ row }">
          <el-switch v-model="row.spuValid" @change="spuValidChange(row)" />
        </el-table-column>
        <el-table-column prop="updated" label="修改时间" width="138" />
        <el-table-column label="操作" fixed="right" width="160" align="center" #default="{ row }">
          <el-button type="primary" icon="Edit" @click="addOrModify(row)" />
          <el-button type="danger" icon="Delete" @click="del(row.id)" />
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
        class="pagination"
        v-model:current-page="listModel.current"
        v-model:page-size="listModel.size"
        :page-sizes="[10, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="pageSizeChange"
        @current-change="fetchListData"
    />

    <el-drawer
        size="50%"
        :title="addOrModifyDrawerTitle"
        v-model="isShowAddOrModifyDrawer"
        direction="rtl"
        :before-close="addOrModifyDrawerClose"
        @opened="addOrModifyDrawerOpened(addOrModifyFormRef)"
    >
      <div class="form-content">
        <el-form ref="addOrModifyFormRef" label-width="70px" :model="addOrModifyModel" :rules="addOrModifyRules">
          <el-form-item label="标题" prop="spuTitle">
            <el-input v-model="addOrModifyModel.spuTitle" placeholder="产品标题" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="分类" prop="spuCategoryId">
            <el-cascader
                v-if="isShowCategoryCascader"
                v-model="addOrModifyModel.spuCategoryId"
                :props="categoryCascaderProps"
                @change="categoryChange"
                placeholder="选择分类" style="width: 360px;" clearable />
          </el-form-item>
          <el-form-item label="品牌" prop="spuBrandId">
            <el-select v-model="addOrModifyModel.spuBrandId" placeholder="选择品牌" clearable>
              <el-option v-for="item in brands" :key="item.id" :label="item.brandName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="品类1" prop="spuSpecCategoryId">
            <el-select v-model="addOrModifyModel.spuSpecCategoryId" placeholder="选择可搜索规格品类" clearable>
              <el-option v-for="item in specCategories" :key="item.id" :label="item.specCategoryName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="品类2" prop="spuSpecNoSearchCategoryId">
            <el-select v-model="addOrModifyModel.spuSpecNoSearchCategoryId" placeholder="选择不可搜索规格品类" clearable>
              <el-option v-for="item in specNoSearchCategories" :key="item.id" :label="item.specCategoryName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="详情" prop="spuImages">
            <my-picture-upload :params="{usage: 'goods'}" :file-list="fileList" @upload-success="uploadSuccess" @remove="removeFile" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="doAddOrModify">
              {{ loading ? '正在提交 ...' : '提交' }}
            </el-button>
            <el-button @click="addOrModifyDrawerClose">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <el-dialog
        v-model="isShowSpuSaleableDialog"
        title="提示"
        width="30%"
        :before-close="cancelChangeSpuSaleable"
    >
      <span>确定要{{ listCurrentRow.spuSaleable ? '上架' : '下架' }}吗？</span>
      <template #footer>
        <span>
          <el-button @click="cancelChangeSpuSaleable">取消</el-button>
          <el-button type="primary" @click="changeSpuSaleable">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="isShowSpuValidDialog"
        title="提示"
        width="30%"
        :before-close="cancelChangeSpuValid"
    >
      <span>确定要{{ listCurrentRow.spuValid ? '有效' : '无效' }}吗？</span>
      <template #footer>
        <span>
          <el-button @click="cancelChangeSpuValid">取消</el-button>
          <el-button type="primary" @click="changeSpuValid">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="isShowDelDialog"
        title="提示"
        width="30%"
        :before-close="delDialogClose"
    >
      <span>确定要删除吗？</span>
      <template #footer>
        <span>
          <el-button @click="delDialogClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="doDel">
            {{ loading ? '正在删除 ...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { saleableList, validList, GetListData, AddData, ModifyData, ModifySaleable, ModifyValid, DeleteData } from '@/api/goods/spu'
import { GetBrandByCategory } from '@/api/goods/brandCategory'
import { GetDataByType } from '@/api/goods/specCategory'
import { GetListData as GetCategories } from "@/api/goods/category"
import MyPictureUpload from '@/components/MyPictureUpload/index.vue'

const loading = ref(false)
const listCurrentRow = ref()
const fileServerUrl = ref(import.meta.env.VITE_FILE_SERVER_URL)

/* 产品上下架开始 */
const isShowSpuSaleableDialog = ref(false)
const spuSaleableChange = row => {
  listCurrentRow.value = row
  isShowSpuSaleableDialog.value = true
}
const cancelChangeSpuSaleable = () => {
  listCurrentRow.value.spuSaleable = !listCurrentRow.value.spuSaleable
  isShowSpuSaleableDialog.value = false
}
const changeSpuSaleable = async () => {
  const { code, message } = await ModifySaleable({
    id: listCurrentRow.value.id,
    spuSaleable: listCurrentRow.value.spuSaleable ? 1 : 0,
  })
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  isShowSpuSaleableDialog.value = false
  ElMessage.success(message)
}
/* 上下架结束 */

/* 产品有效/无效开始 */
const isShowSpuValidDialog = ref(false)
const spuValidChange = row => {
  listCurrentRow.value = row
  isShowSpuValidDialog.value = true
}
const cancelChangeSpuValid = () => {
  listCurrentRow.value.spuValid = !listCurrentRow.value.spuValid
  isShowSpuValidDialog.value = false
}
const changeSpuValid = async () => {
  const { code, message } = await ModifyValid({
    id: listCurrentRow.value.id,
    spuValid: listCurrentRow.value.spuValid ? 1 : 0,
  })
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  isShowSpuValidDialog.value = false
  ElMessage.success(message)
}
/* 产品有效/无效结束 */

const listBrands = ref([])
const fetchListBrands = async id => {
  const { code, message, data } = await GetBrandByCategory(id)
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  listBrands.value = data
}
const brands = ref([])
const fetchBrands = async id => {
  const { code, message, data } = await GetBrandByCategory(id)
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  brands.value = data
}

const listCascaderProps = {
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const { level } = node
    let parentId = 0
    if (level > 0) {
      parentId = node.value
    }
    const { code, message, data } = await GetCategories(parentId)
    if (code !== 200) {
      ElMessage.error(message)
      return
    }
    const nodes = data.map(item => ({
      value: item.id,
      label: item.categoryName,
      leaf: !item.hasChildren,
    }))
    await resolve(nodes)
  },
}

const listCategoryChange = () => {
  const ids = listModel.value.spuCategoryId
  if (Array.isArray(ids)) {
    listModel.value.spuCategoryId = ids[ids.length - 1]
  }
  fetchListBrands(listModel.value.spuCategoryId)
}

const specCategories = ref([])
const specNoSearchCategories = ref([])
const fetchSpecCategories = async () => {
  const { code, message, data } = await GetDataByType(1)
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  specCategories.value = data
}
const fetchSpecNoSearchCategories = async () => {
  const { code, message, data } = await GetDataByType(2)
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  specNoSearchCategories.value = data
}

/* 列表开始 */
const total = ref(0)
const listModelData = {
  current: 1,
  size: Number(import.meta.env.VITE_PAGE_SIZE),
  spuTitle: '',
  spuCategoryId: '',
  spuBrandId: '',
  spuSaleable: '',
  spuValid: '',
}
const listModel = ref({ ...listModelData })
const listData = ref([])

const selectionChange = arr => {
  delModel.value.ids = []
  arr.forEach(row => {
    delModel.value.ids.push(row.id)
  })
}

const fetchListData = async () => {
  if (loading.value) {
    return
  }
  loading.value = true
  const { code, message, data } = await GetListData(listModel.value)
  loading.value = false
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  listData.value = data.records
  data.records.map(item => {
    item.spuSaleable = item.spuSaleable === 1
    item.spuValid = item.spuValid === 1
  })
  total.value = Number(data.total)
}

const pageSizeChange = () => {
  listModel.value.current = 1
  fetchListData()
}

const resetList = () => {
  listModel.value = { ...listModelData }
  fetchListData()
}

onMounted(() => {
  fetchSpecCategories()
  fetchSpecNoSearchCategories()
  fetchListData()
})
/* 列表结束 */

/* 上传图片开始 */
const fileList = ref([])
const uploadFileList = ref([]) // 最终的图片保存在这里

const uploadSuccess = file => {
  uploadFileList.value.push(file)
}

const removeFile = files => {
  uploadFileList.value = []
  files.forEach(item => {
    let name = item.name
    if (item.response) {
      name = item.response.data.name
    }
    uploadFileList.value.push(name)
  })
  ElMessage.success('删除成功')
}
/* 上传图片结束 */

/* 添加修改开始 */
const addOrModifyCurrentRow = ref()
const isShowCategoryCascader = ref(false)
const addOrModifyFormRef = ref()
const addOrModifyDrawerTitle = ref('')
const isShowAddOrModifyDrawer = ref(false)

const addOrModifyData = {
  spuTitle: '',
  spuBrandId: '',
  spuCategoryId: '',
  spuSpecCategoryId: '',
  spuSpecNoSearchCategoryId: '',
  spuImages: '',
}
const addOrModifyModel = ref({ ...addOrModifyData })

const addOrModifyRules = ref({
  spuTitle: [{ required: true, message: '请输入产品标题', trigger: 'blur' }],
  spuBrandId: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
  spuCategoryId: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  spuSpecNoSearchCategoryId: [{ required: true, message: '请选择不可搜索规格品类', trigger: 'blur' }],
  spuImages: [{ required: true, message: '请上传产品详情图片', trigger: 'blur' }],
})

const categoryCascaderProps = {
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const { level } = node
    let parentId = 0
    if (level > 0) {
      parentId = node.value
    }
    const { code, message, data } = await GetCategories(parentId)
    if (code !== 200) {
      ElMessage.error(message)
      return
    }
    const nodes = data.map(item => ({
      value: item.id,
      label: item.categoryName,
      leaf: !item.hasChildren,
    }))
    if (addOrModifyCurrentRow.value) {
      const row = addOrModifyCurrentRow.value
      if (row.spuCategoryId && row.spuCategoryId.length > 0 && level <= 0) {
        nodes.push({
          value: row.spuCategoryId,
          label: `${row.firstCategoryName} / ${row.secondCategoryName} / ${row.thirdCategoryName}`,
          leaf: true,
        })
      }
    }
    await resolve(nodes)
  },
}

const categoryChange = async () => {
  if (Array.isArray(addOrModifyModel.value.spuCategoryId)) {
    const lastIndex = addOrModifyModel.value.spuCategoryId.length - 1
    addOrModifyModel.value.spuCategoryId = addOrModifyModel.value.spuCategoryId[lastIndex]
  }
  await fetchBrands(addOrModifyModel.value.spuCategoryId)
}

const addOrModify = (row) => {
  if (row == null) {
    addOrModifyDrawerTitle.value = '添加产品SPU'
  } else {
    addOrModifyCurrentRow.value = row
    addOrModifyDrawerTitle.value = '编辑产品SPU'
    addOrModifyModel.value = { ...row }
    delete addOrModifyModel.value.spuSaleable
    delete addOrModifyModel.value.spuValid
    delete addOrModifyModel.value.created
    delete addOrModifyModel.value.updated
    fetchBrands(row.spuCategoryId)
    const spuImages = JSON.parse(row.spuImages).desc
    if (spuImages.length > 0) {
      spuImages.forEach(item => {
        uploadFileList.value.push(item)
        fileList.value.push({
          name: item,
          url: `${fileServerUrl.value}${item}`
        })
      })
    }
  }
  isShowAddOrModifyDrawer.value = true
  isShowCategoryCascader.value = true
}

const doAddOrModify = () => {
  if (loading.value) {
    return
  }
  if (uploadFileList.value.length > 0) {
    addOrModifyModel.value.spuImages = JSON.stringify({
      desc: uploadFileList.value
    })
  }
  addOrModifyFormRef.value.validate(async valid => {
    if (!valid) {
      return
    }
    loading.value = true
    let code, message
    if (addOrModifyModel.value.id) {
      const result = await ModifyData(addOrModifyModel.value)
      code = result.code
      message = result.message
    } else {
      const result = await AddData(addOrModifyModel.value)
      code = result.code
      message = result.message
    }
    loading.value = false
    if (code !== 200) {
      ElMessage.error(message)
      return
    }
    isShowAddOrModifyDrawer.value = false
    resetAddOrModify()
    await fetchListData()
    ElMessage.success(message)
  })
}

const addOrModifyDrawerOpened = formEl => {
  formEl.clearValidate()
}

const resetAddOrModify = () => {
  fileList.value = []
  uploadFileList.value = []
  isShowCategoryCascader.value = false
  addOrModifyFormRef.value.resetFields()
  addOrModifyModel.value = { ...addOrModifyData }
  loading.value = false
}

const addOrModifyDrawerClose = () => {
  if (loading.value) {
    return
  }
  resetAddOrModify()
  isShowAddOrModifyDrawer.value = false
}
/* 添加修改结束 */

/* 删除开始 */
const isShowDelDialog = ref(false)
const delModel = ref({ ids: [] })

const del = id => {
  delModel.value.ids.push(id)
  isShowDelDialog.value = true
}

const doDel = async () => {
  if (loading.value) {
    return
  }
  if (delModel.value.ids.length <= 0) {
    ElMessage.error('请至少选择一项')
    return
  }
  loading.value = true
  const { code, message } = await DeleteData(delModel.value)
  loading.value = false
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  isShowDelDialog.value = false
  resetDel()
  await fetchListData()
  ElMessage.success(message)
}

const resetDel = () => {
  delModel.value.ids = []
  loading.value = false
}

const delDialogClose = () => {
  if (loading.value) {
    return
  }
  resetDel()
  isShowDelDialog.value = false
}
/* 删除结束 */
</script>

<style scoped lang="scss">
.page-box {
  width: 100%;
  box-sizing: border-box;
  .search {
    padding: 20px 20px 0;
    background: #fff;
    margin-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      margin: {
        right: 10px;
        bottom: 20px;
      }
    }
    .search-btn {
      margin-left: auto;
    }
    :deep(.el-input-number .el-input__inner) {
      text-align: left;
    }
    :deep(.el-range-editor.el-input__wrapper) {
      box-sizing: border-box;
    }
  }
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 20px 0;
    background: #fff;
    .title {
      font-size: 16px;
    }
  }
  .table {
    padding: 20px;
    background: #fff;
  }
  .pagination {
    padding: 0 20px 20px;
    background: #fff;
    justify-content: flex-end;
    :last-child {
      margin-right: 0;
    }
  }
  .form-content {
    /* 上传组件的样式开始 */
    .uploader {
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }
      :deep(.el-upload:hover) {
        border-color: var(--el-color-primary);
      }
      :deep(.uploader-icon) {
        font-size: 28px;
        color: #8c939d;
        width: 160px;
        height: 140px;
        text-align: center;
      }
    }
    /* 上传组件的样式结束 */
  }
}
</style>